<?php
/**
 * Magento
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Academic Free License (AFL 3.0)
 * that is bundled with this package in the file LICENSE_AFL.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magentocommerce.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Magento to newer
 * versions in the future. If you wish to customize Magento for your
 * needs please refer to http://www.magentocommerce.com for more information.
 *
 * @copyright   Copyright (c) 2014 X.commerce, Inc. (http://www.magentocommerce.com)
 * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 */
?>
<?php
/**
 * Template for \Magento\Catalog\Block\Adminhtml\Category\Cointainer
 */
?>

<div id="category-edit-container" class="category-content">
    <?php echo $this->getChildHtml('form') ?>
</div>
<script type="text/javascript">
require([
    "jquery",
    "js/theme",
    "mage/backend/floating-header"
], function(jQuery){

//<![CDATA[
    function categoryReset(url,useAjax){
        if(useAjax){
            var params = {active_tab_id:false};
            updateContent(url, params);
        }else{
            location.href = url;
        }
    }

    /**
    * Delete some category
    * This routine get categoryId explicitly, so even if currently selected tree node is out of sync
    * with this form, we surely delete same category in the tree and at backend
    */
    function categoryDelete(url, useAjax, categoryId) {
        if (confirm('<?php echo __('Are you sure you want to delete this category?') ?>')){
            if (useAjax){
                tree.nodeForDelete = categoryId;
                updateContent(url, {}, true);
            } else {
                location.href = url;
            }
        }
    }

    /**
     * Update category content area
     */
    function updateContent(url, params, refreshTree) {
        var win = this;
        var params = jQuery.extend(params || {}, {
            form_key: FORM_KEY
        });

        if (params.node_name) {
            this.tree.getNodeById(tree.currentNodeId).currentNode.setText(params.node_name);
        }

        (function($){
            var $categoryContainer = $('#category-edit-container');
            $.ajax({
                url: url + (url.match(new RegExp('\\?')) ? '&isAjax=true' : '?isAjax=true' ),
                data: params,
                context: $('body'),
                showLoader: true
            }).done(function(data){
                if (data.content) {
                    $('.page-actions').floatingHeader('destroy');
                    try {
                        $('#category-edit-container .wysiwyg-editor').each(function(index, element) {
                            tinyMCE.execCommand('mceRemoveControl', false, $(element).attr('id'));
                        });
                        $categoryContainer.html('');
                    } catch(e) {
                        alert(e.message);
                    }
                    $categoryContainer.html(data.content).trigger('contentUpdated');
                    setTimeout(function() {
                        $('#category-edit-container .wysiwyg-editor').each(function(index, element) {
                            tinyMCE.execCommand('mceRemoveControl', false, $(element).attr('id'));
                            tinyMCE.execCommand('mceAddControl', true, $(element).attr('id'));
                        });
                        $('.page-actions').floatingHeader({ 'title': '.category-edit-title'});
                        try {
                            if (refreshTree) {
                                win.refreshTreeArea();
                            }
                        } catch (e) {
                            alert(e.message);
                        };
                    }, 25);
                }
                if (data.messages && data.messages.length > 0) {
                    $('.messages').html(data.messages);
                }
            });
        })(jQuery);
    }

    /**
     * Refresh tree nodes after saving or deleting a category
     */
    function refreshTreeArea(transport)
    {
        if (tree && window.editingCategoryBreadcrumbs) {
            // category deleted - delete its node
            if (tree.nodeForDelete) {
                var node = tree.getNodeById(tree.nodeForDelete);
                tree.nodeForDelete = false;

                if (node) { // Check maybe tree became somehow not synced with ajax and we're trying to delete unknown node
                    node.parentNode.removeChild(node);
                    tree.currentNodeId = false;
                }
            }
            // category created - add its node
            else if (tree.addNodeTo) {
                var parent = tree.getNodeById(tree.addNodeTo);
                tree.addNodeTo = false;

                if (parent) { // Check maybe tree became somehow not synced with ajax and we're trying to add to unknown node
                    var node = new Ext.tree.AsyncTreeNode(editingCategoryBreadcrumbs[editingCategoryBreadcrumbs.length - 1]);
                    node.loaded = true;
                    tree.currentNodeId = node.id;
                    parent.appendChild(node);

                    if (parent.expanded) {
                        tree.selectCurrentNode();
                    } else {
                        var timer;
                        parent.expand();
                        var f = function(){
                            if(parent.expanded){ // done expanding
                                clearInterval(timer);
                                tree.selectCurrentNode();
                            }
                        };
                        timer = setInterval(f, 200);
                    }
                }
            }

            // update all affected categories nodes names
            for (var i = 0; i < editingCategoryBreadcrumbs.length; i++) {
                var node = tree.getNodeById(editingCategoryBreadcrumbs[i].id);
                if (node) {
                    node.setText(editingCategoryBreadcrumbs[i].text);
                }
            }
        }
    }

    function displayLoadingMask() {
        jQuery('body').loadingPopup();
    }

    window.refreshTreeArea = refreshTreeArea;
    window.updateContent = updateContent;
    window.categoryDelete = categoryDelete;
    window.categoryReset = categoryReset;
    window.displayLoadingMask = displayLoadingMask;
//]]>

});
</script>
